package be.sc.classicnetwork.controller.validator;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.hibernate.validator.MessageInterpolator;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * EntityValidator.
 */
public class EntityValidator implements Validator {

	/**
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	public boolean supports(Class clazz) {
		return true;
	}

	/**
	 * @see org.springframework.validation.Validator#validate(java.lang.Object,
	 *      org.springframework.validation.Errors)
	 */
	@SuppressWarnings("unchecked")
	public void validate(Object target, Errors errors) {
		ClassValidator classValidator = new ClassValidator(target.getClass(),
				new MessageInterpolator() {

					public String interpolate(String message,
							org.hibernate.validator.Validator validator,
							MessageInterpolator messageInterpolator) {
						return message;
					}

				});
		InvalidValue[] invalidValues = classValidator.getInvalidValues(target);
		for (InvalidValue invalidValue : invalidValues) {
			// if global error
			if (invalidValue.getPropertyPath() == null) {
				errors.reject(invalidValue.getMessage());
			} else {
				errors.rejectValue(invalidValue.getPropertyPath(), invalidValue
						.getMessage());
			}
		}
	}

}
